package com.demo.support.util;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import com.demo.support.util.File.FileTypeUtil;
import com.jweb.util.FormatUtil;

public class OperateImage {

	// ===源图片路径名称如：c:\1.jpg
	private String srcpath;

	// ===剪切图片存放路径名称。如：c:\2.jpg
	private String subpath;

	public void setSrcpath(String srcpath) {
		this.srcpath = srcpath;
	}

	public void setSubpath(String subpath) {
		this.subpath = subpath;
	}

	private String fileType;
	// ===剪切点x坐标
	private int x;

	private int y;

	// ===剪切点宽度
	private int width;
	private int height;
	// ===图片缩放宽高，，默认原始宽度
	private int defWidth;
	private int defHeight;

	public OperateImage() {
	}

	/**
	 * 頭像剪切
	 * 
	 * @param x
	 *            x轴
	 * @param y
	 *            y轴
	 * @param width
	 *            剪切宽度
	 * @param height
	 *            剪切高度
	 * @param defWidth
	 *            压缩后宽度
	 * @param defHeight
	 *            压缩后高度
	 * @param fileType
	 *            文件类型
	 */
	public OperateImage(int x, int y, int width, int height, int defWidth,
			int defHeight, String fileType) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.defHeight = defHeight;
		this.defWidth = defWidth;
		this.fileType = fileType;
	}

	/**
	 * 
	 * 对图片裁剪，并把裁剪完蛋新图片保存 。
	 * 
	 * @throws Exception
	 */

	public void cut(InputStream fis) throws Exception {
		ImageInputStream iis = null;
		try {
			if (!FormatUtil.isEmpty(fileType)) {

				InputStream ins = zoomImage(fis, defWidth, defHeight, fileType);
				// 读取图片文件
				Iterator<ImageReader> it = ImageIO
						.getImageReadersByFormatName(fileType);
				ImageReader reader = it.next();
				iis = ImageIO.createImageInputStream(ins);
				reader.setInput(iis, true);
				ImageReadParam param = reader.getDefaultReadParam();
				Rectangle rect = new Rectangle(x, y, width, height);
				param.setSourceRegion(rect);
				BufferedImage bi = reader.read(0, param);
				// 保存新图片
				ImageIO.write(bi, fileType, new File(subpath));
			} else {
				System.err.println("不支持的文件类型");
			}
		} finally {
			if (fis != null)
				fis.close();
			if (iis != null)
				iis.close();
		}

	}

	/*
	 * 图片缩放
	 */
	public InputStream zoomImage(InputStream src, int w, int h, String file_type)
			throws Exception {
		double wr = 0, hr = 0;
		BufferedImage bufImg = ImageIO.read(src);
		if (w == 0 && h == 0)
			throw new Exception("缩放必须设置一个值");
		if (w == 0)
			w = (int) (h * 1.00 / bufImg.getHeight() * bufImg.getWidth());
		if (h == 0)
			h = (int) (w * 1.00 / bufImg.getWidth() * bufImg.getHeight());
		wr = w * 1.00 / bufImg.getWidth();
		hr = h * 1.00 / bufImg.getHeight();
		Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);
		AffineTransformOp ato = new AffineTransformOp(
				AffineTransform.getScaleInstance(wr, hr), null);
		Itemp = ato.filter(bufImg, null);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ImageIO.write((BufferedImage) Itemp, file_type, os);
		InputStream is = new ByteArrayInputStream(os.toByteArray());
		return is;
	}

	public static void main(String[] args) {
		try {
			String fileType = "jpg";
			InputStream input = new FileInputStream("d:\\bb.jpg");
			OperateImage oi = new OperateImage();
			InputStream is = oi.zoomImage(input, 1920, 0, fileType);
			// 通过available方法取得流的最大字符数
			ImageIO.write(ImageIO.read(is), fileType, new File("d:\\bb2.jpg"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main2(String[] args) throws Exception {
		InputStream input = new FileInputStream("d:\\bb.jpg");
		// ======== 缓冲输入流 ========
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		while ((len = input.read(buffer)) > -1)
			baos.write(buffer, 0, len);
		baos.flush();
		// ========== 缓冲读取输入流,判断类型 ===========
		InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());
		String fileType = FileTypeUtil.getFileByFile(stream1);
		// ========== 缓冲读取输入流,转换压缩 ============
		InputStream stream2 = new ByteArrayInputStream(baos.toByteArray());

		System.out.println("fileType:" + fileType);
		OperateImage o = new OperateImage(65, 18, 128, 128, 234, 155, fileType);
		o.setSubpath("D:\\bb2.jpg");
		o.cut(stream2);
	}

}